package org.example.company.handler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.common.Constant;
import org.example.company.config.JwtProperties;
import org.example.company.entity.AuthUserDetails;
import org.example.company.service.SecurityUserDetailService;
import org.example.company.utils.JwtTokenUtils;
import org.example.response.RespnseResult;
import org.example.response.ResultCode;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
@Component
public class AuthenticationSuceessHandler extends WebFilterChainServerAuthenticationSuccessHandler {

    public final SecurityUserDetailService securityUserDetailService;

    public final JwtProperties jwtProperties;

    public AuthenticationSuceessHandler(JwtProperties jwtProperties, SecurityUserDetailService securityUserDetailService) {
        this.jwtProperties = jwtProperties;
        this.securityUserDetailService = securityUserDetailService;
    }

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        //设置headers
        headers.add("Content-Type","application/json;charset=UTF-8");
        headers.add("Cache-Control","no-store,no-cache,must-revalidate,max-age-8");
        //设置body
        RespnseResult<AuthUserDetails> result = RespnseResult.success();
        byte[] dataBytes={};
        ObjectMapper mapper = new ObjectMapper();
        try {
            User user= (User)authentication.getPrincipal();
            AuthUserDetails  buildUser= buildUser(user);
            HashMap<String, Object> map = new HashMap<>(2);
            map.put(Constant.TOKEN_USER_INFO,buildUser);
            //生成token
            String jwtToken = JwtTokenUtils.createWebTokenJwtAuth(map,jwtProperties.getSecurityKey(),jwtProperties.getValidateInMs());
            buildUser.setToken(jwtToken);
            result.setData(buildUser);
            dataBytes= mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            HashMap<String, Object> map = new HashMap<>(4);
            map.put("status", ResultCode.UNAUTHORIZED.getCode());
            map.put("msg",ResultCode.UNAUTHORIZED.getMsg());
            byte[] toJSONBytes = JSON.toJSONString(map).getBytes();
        }
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDataBuffer));
    }

    private AuthUserDetails buildUser(User user){
        AuthUserDetails authUserDetails = new AuthUserDetails();
        authUserDetails.setUsername(user.getUsername());
        authUserDetails.setPassword(new BCryptPasswordEncoder().encode("123456"));
        authUserDetails.setRole("admin");
        return authUserDetails;
    }
}
